package connection;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.squareapp.R;
import com.squareapp.R.id;
import com.squareapp.R.layout;
import com.squareapp.R.menu;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.os.Build;

public class GooglePlusActivity extends ActionBarActivity implements View.OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {

	private static final String TAG = "MainActivity";
	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;

	private ProgressDialog mConnectionProgressDialog;
	private PlusClient mPlusClient;
	private ConnectionResult mConnectionResult;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_google_plus);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
		
		findViewById(R.id.btn_sign_in).setOnClickListener(this);
		mPlusClient = new PlusClient.Builder(this, this, this)
		        .setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
		        .setScopes(Scopes.PLUS_LOGIN)  // recommended login scope for social features
		        // .setScopes("profile")       // alternative basic login scope
		        .build();
		// Progress bar to be displayed if the connection failure is not resolved.
		mConnectionProgressDialog = new ProgressDialog(this);
		mConnectionProgressDialog.setMessage("Signing in...");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.google_plus, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_google_plus,
					container, false);
			return rootView;
		}
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (mConnectionProgressDialog.isShowing()) {
			// The user clicked the sign-in button already. Start to resolve
			// connection errors. Wait until onConnected() to dismiss the
			// connection dialog.
			if (result.hasResolution()) {
			  try {
			           result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
			   } catch (SendIntentException e) {
			           mPlusClient.connect();
			   }
			}
			}
			// Save the result and resolve the connection failure upon a user click.
			mConnectionResult = result;
		
	}

	@Override
	protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
	if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
	    mConnectionResult = null;
	    mPlusClient.connect();
	}
	}
	
	@Override
	public void onConnected(Bundle connectionHint) {
		String accountName = mPlusClient.getAccountName();
		Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
	}


	@Override
	public void onClick(View view) {
	    if (view.getId() == R.id.btn_sign_in && !mPlusClient.isConnected()) {
	        if (mConnectionResult == null) {
	            mConnectionProgressDialog.show();
	        } else {
	            try {
	                mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
	            } catch (SendIntentException e) {
	                // Try connecting again.
	                mConnectionResult = null;
	                mPlusClient.connect();
	            }
	        }
	    }
	}

	@Override
	public void onDisconnected() {
		Log.d(TAG, "disconnected");
	}
	 
	@Override
	protected void onStart() {
	super.onStart();
	mPlusClient.connect();
	}

	@Override
	protected void onStop() {
	super.onStop();
	mPlusClient.disconnect();
	}

}
